/**
 * 为用户快照表添加管理员字段的迁移脚本
 * 包含 isAdmin, isSuperAdmin, isMuted, adminPrivileges 字段
 */

const { sequelize } = require('../dist/config/database');

async function addAdminFields() {
  try {
    console.log('🚀 开始为用户快照表添加管理员字段...');
    
    // 连接数据库
    await sequelize.authenticate();
    console.log('✅ 数据库连接成功');
    
    // 检查表是否存在
    const [tables] = await sequelize.query(`
      SELECT name FROM sqlite_master WHERE type='table' AND name='user_snapshots';
    `);
    
    if (tables.length === 0) {
      console.log('❌ user_snapshots 表不存在，请先运行数据库初始化');
      process.exit(1);
    }
    
    // 获取当前表结构
    const [columns] = await sequelize.query(`
      PRAGMA table_info(user_snapshots);
    `);
    
    const existingColumns = columns.map(col => col.name);
    console.log('📋 当前表字段:', existingColumns.join(', '));
    
    // 定义要添加的管理员字段
    const adminFields = [
      {
        name: 'isMuted',
        sql: 'ALTER TABLE user_snapshots ADD COLUMN "isMuted" BOOLEAN DEFAULT FALSE;',
        description: '用户是否被禁言'
      },
      {
        name: 'isAdmin',
        sql: 'ALTER TABLE user_snapshots ADD COLUMN "isAdmin" BOOLEAN DEFAULT FALSE;',
        description: '用户是否为管理员'
      },
      {
        name: 'isSuperAdmin',
        sql: 'ALTER TABLE user_snapshots ADD COLUMN "isSuperAdmin" BOOLEAN DEFAULT FALSE;',
        description: '用户是否为超级管理员'
      },
      {
        name: 'adminPrivileges',
        sql: 'ALTER TABLE user_snapshots ADD COLUMN "adminPrivileges" TEXT;',
        description: '管理员权限列表（JSON字符串格式）'
      }
    ];
    
    // 添加缺失的字段
    let addedCount = 0;
    
    for (const field of adminFields) {
      if (!existingColumns.includes(field.name)) {
        try {
          console.log(`➕ 添加字段: ${field.name} - ${field.description}`);
          await sequelize.query(field.sql);
          addedCount++;
          console.log(`   ✅ ${field.name} 字段添加成功`);
        } catch (error) {
          console.error(`   ❌ 添加 ${field.name} 字段失败:`, error.message);
        }
      } else {
        console.log(`   ⏭️  ${field.name} 字段已存在，跳过`);
      }
    }
    
    // 创建索引以提高查询性能
    const indexes = [
      {
        name: 'user_snapshots_is_admin',
        sql: 'CREATE INDEX IF NOT EXISTS "user_snapshots_is_admin" ON "user_snapshots" ("isAdmin");'
      },
      {
        name: 'user_snapshots_is_super_admin',
        sql: 'CREATE INDEX IF NOT EXISTS "user_snapshots_is_super_admin" ON "user_snapshots" ("isSuperAdmin");'
      },
      {
        name: 'user_snapshots_is_muted',
        sql: 'CREATE INDEX IF NOT EXISTS "user_snapshots_is_muted" ON "user_snapshots" ("isMuted");'
      }
    ];
    
    console.log('\n🔍 创建索引以提高查询性能...');
    for (const index of indexes) {
      try {
        await sequelize.query(index.sql);
        console.log(`   ✅ 索引 ${index.name} 创建成功`);
      } catch (error) {
        console.log(`   ⚠️  索引 ${index.name} 可能已存在:`, error.message);
      }
    }
    
    // 验证添加结果
    console.log('\n🔍 验证添加结果...');
    const [newColumns] = await sequelize.query(`
      PRAGMA table_info(user_snapshots);
    `);
    
    const newColumnNames = newColumns.map(col => col.name);
    const adminFieldNames = adminFields.map(field => field.name);
    const allAdminFieldsExist = adminFieldNames.every(field => newColumnNames.includes(field));
    
    if (allAdminFieldsExist) {
      console.log('🎉 所有管理员字段添加完成！');
      console.log(`📊 本次添加了 ${addedCount} 个新字段`);
      
      // 显示最终的管理员字段
      console.log('\n🔐 管理员字段列表:');
      adminFieldNames.forEach(field => {
        const column = newColumns.find(col => col.name === field);
        if (column) {
          console.log(`   - ${field}: ${column.type} ${column.dflt_value ? `DEFAULT ${column.dflt_value}` : ''}`);
        }
      });
    } else {
      console.log('❌ 部分管理员字段添加失败');
    }
    
    await sequelize.close();
    console.log('\n✅ 迁移完成');
    
  } catch (error) {
    console.error('❌ 迁移失败:', error);
    process.exit(1);
  }
}

// 运行迁移
addAdminFields();